package com.kzw.web;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import com.kzw.entity.User;
import com.kzw.service.UserService;

import my.bean.Msg;
import my.db.Page;
import my.mvc.Annotation.JSON;
import my.mvc.RequestContext;

public class RegisterAction {

	private UserService service = new UserService();
	@JSON
	public Msg exist(RequestContext rc) {
		String uname = rc.param("uname");	
		Msg msg = new Msg();	
		User user = service.RegistUser(uname,"","");
		if(user == null) {
			msg.setSuccess(false);
			msg.setMsg("用户名已存在");
		} else {
			msg.setSuccess(true);
			msg.setMsg("用户名可以使用");
		}		
		return msg;
	}
	
	@JSON
	public Msg index(RequestContext rc) {
		String uname = rc.param("uname");
		String passwd = rc.param("passwd");
		String email = rc.param("email");	
		Msg msg = new Msg();	
		User user = service.RegistUser(uname, passwd, email);
		if(user == null) {
			msg.setSuccess(false);
			msg.setMsg("注册失败");
		} else {
			rc.sessionAttr("USER", user);
		}		
		return msg;
	}
	
	public Msg addUser(RequestContext rc) {
		User a = rc.form(User.class);
		Msg msg = new Msg();	
		User user = service.RegistUser(a.getUname(),a.getPasswd(),a.getEmail(),a.getMoney());
		if(user == null) {
			msg.setSuccess(false);
			msg.setMsg("注册失败");
		} else {
			rc.sessionAttr("USER", user);
		}		
		return msg;
	}
	@SuppressWarnings("unchecked")
	@JSON
	public Page<User> list(RequestContext rc) {
		// 获得分页信息, layui表格分页参数：page、limit
		Page<User> page = rc.form(Page.class);
		String title = rc.param("uname");
		service.list(page, title);		
		return page;
	}
	@JSON
	public Msg save(RequestContext rc) throws Exception {
		User a = rc.form(User.class);
		if(a.getId() == 0) {
			return addUser(rc);
		} else {
			User b=service.FindUser(a.getId());
			if(b.getPasswd().equals(a.getPasswd())) {
				service.update(a);
			}
			else {
				b.setPasswd(DigestUtils.md5Hex(b.getPasswd()));
				service.update(b);
			}
			return new Msg(true,1,"更新成功！");
		}
	}
	
	public Msg multiDel(RequestContext rc) {
		String ids = rc.param("ids");
		if(StringUtils.isNotBlank(ids)) {
			String[] arr = ids.split(",");
			for(String id : arr) {
				service.delete(Long.parseLong(id));
			}
		}
		return new Msg();
	}
	
	public void get(RequestContext rc) {
		long id = rc.param("id", 0L);
		User user = service.get(id);
		rc.reqAttr("user", user);
		rc.forward("/page/user/user_form.jsp");
	}
}
